package demo;

import java.util.List;

public class MySingleList implements ILinkedList {

    //定义静态内部类来表现节点对象
    static class ListNode{
        //数据
        public int val;
        //节点的引用
        public ListNode next;

        public ListNode (int val){
            this.val = val;
        }
    }
    //存储表的头节点引用
    public  ListNode head;
    @Override
    public void addFirst(int data) {
        //让一个数字变成接节点
        ListNode node = new ListNode(data);
        node.next = head;
        head = node;
    }

    @Override
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        ListNode cur = this.head;
        if(head==null){
            head = node;
            return;
        }
        while(cur.next != null){
            cur = cur.next;
        }
        cur.next = node;
    }

    @Override
    public void addIndex(int index, int data) {
            CheckPos(index);
            if(index==0){
                addFirst(data);
                return;
            }
            if(index==size()){
                addLast(data);
                return;
            }

        ListNode cur = findIndex(index);
        ListNode node = new ListNode(data);

        node.next = cur.next;
        cur.next = node;
    }

    private ListNode findIndex(int index){
        ListNode cur = head;
        int count = 0;
        while(count != index-1){
            cur = cur.next;
            count++;
        }
        return cur;
    }

    private void CheckPos(int index){
        if(index <0||index > size()){
            throw new CheckPosException("index位置不合法："+index);
        }
    }
    @Override
    public boolean contains(int key) {
       ListNode cur = this.head;
       while(cur != null){
           if(cur.val == key){
               return true;
           }
           cur = cur.next;
       }
       return false;
    }

    @Override
    public void remove(int key) {

    }

    @Override
    public void removeAllKey(int key) {

    }

    @Override
    public int size() {
        ListNode cur = this.head;
        int count = 0;
        while(cur != null){
            count++;
            cur = cur.next;
        }
        return count;
    }

    @Override
    public void clear() {

    }

    @Override
    public void display() {
        ListNode cur = this.head;
        while(cur != null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
}